<template>
  <router-view v-slot="{ Component }">
    <transition
      :name="transitionName"
      @before-enter="beforeEnter"
      @after-leave="afterLeave"
    >
      <component
        :is="Component"
        :class="{
          'fixed left-0 top-0 w-screen z-1000': isAnimation
        }"
        :key="$route.fullPath"
      ></component>
    </transition>
  </router-view>
</template>
<script>
const NONE = 'none'
const ROUTER_TYPE_PUSH = 'push'
const ROUTER_TYPE_BACK = 'back'
const ROUTER_TYPE_ENUM = [NONE, ROUTER_TYPE_PUSH, ROUTER_TYPE_BACK]
</script>
<script setup>
import { useRouter } from 'vue-router'
import { ref } from 'vue'
const router = useRouter()
const props = defineProps({
  //路由的跳转类型，进入组件、离开组件
  routerType: {
    type: String,
    default: NONE,
    validator(val) {
      const res = ROUTER_TYPE_ENUM.includes(val)
      if (!res) {
        throw new Error(
          `routerType 参数错误，请传入 ${ROUTER_TYPE_ENUM.join('、')} 中的值`
        )
      }
      return res
    }
  }
})
const transitionName = ref('')
router.beforeEach((to, from) => {
  transitionName.value = props.routerType
})
const isAnimation = ref(false)
const beforeEnter = () => {
  isAnimation.value = true
}
const afterLeave = () => {
  isAnimation.value = false
}
</script>
<style lang="less" scoped>
.push-enter-active {
  animation-name: push-in;
  animation-duration: 0.4s;
}
.push-leave-active {
  animation-name: push-out;
  animation-duration: 0.4s;
}
@keyframes push-in {
  0% {
    transform: translate(100%, 0);
  }
  100% {
    transform: translate(0, 0);
  }
}
@keyframes push-out {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(-50%, 0);
  }
}
.back-enter-active {
  animation-name: back-in;
  animation-duration: 0.4s;
}
.back-leave-active {
  animation-name: back-out;
  animation-duration: 0.4s;
}
@keyframes back-in {
  0% {
    width: 100%;
    transform: translate(-100%, 0);
  }
  100% {
    width: 100%;
    transform: translate(0, 0);
  }
}
@keyframes back-out {
  0% {
    width: 100%;
    transform: translate(0, 0);
  }
  100% {
    width: 100%;
    transform: translate(50%, 0);
  }
}
</style>
